package com.sdonkey.score.controller;

import com.sdonkey.score.bean.UserLoginBean;
import com.sdonkey.score.bean.UserLoginInfoBean;
import com.sdonkey.score.dto.SystemInfo;
import com.sdonkey.score.dto.UserInfoDto;
import com.sdonkey.score.service.IUserLoginService;
import com.sdonkey.score.service.IJedisService;
import com.sdonkey.score.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录/找回密码模块
 *
 * @author ZhaoShihao
 * @version 1.0
 */
@Controller
@RequestMapping(method = RequestMethod.POST)
public class UserLoginController {
    private Logger logger = Logger.getLogger(UserLoginController.class);
    @Autowired
    private IUserLoginService userLoginService;
    @Autowired
    private IJedisService IJedisService;

    /**
     * 获取用户记住密码信息并通过json返回
     *
     * @param request 请求：获取cookie
     * @return 用户信息
     */
    @RequestMapping(value = "/ajaxGetUserRemember")
    @ResponseBody
    public UserLoginInfoBean ajaxGetUserRemember(HttpServletRequest request) {
        return IJedisService.getUserByRedis(request);
    }

    /**
     * 用户登录
     *
     * @param flag       用户是否修改了密码(修改了密码该值为空)
     * @param info       用户登录信息
     * @param rememberMe 是否记住密码（不记住密码该值为空）
     * @param session    会话
     * @return
     */
    @RequestMapping(value = "/ajaxDoLogin")
    @ResponseBody
    public Map<String, Object> ajaxDoLogin(Integer flag, UserLoginInfoBean info,
                                           Integer rememberMe, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        try {
            UserLoginBean userLoginBean = null;
            session.setMaxInactiveInterval(60 * 30);
            String username = info.getUsername();
            String login_password = info.getPassword();
            if (flag != null && flag == 1) {
                userLoginBean = userLoginService.userLogin(username, SymmetricEncoder.AESDncode(username, login_password));
            } else {
                userLoginBean = userLoginService.userLogin(username, login_password);
            }
            if (userLoginBean != null) {
                if (Integer.valueOf(userLoginBean.getLogin_status()) < 0) {
                    map.put("message", "-2");
                    logger.info("用户" + username + " 被冻结，登录失败！");
                    return map;
                }
                userLoginBean.setImage_url(StaticVariable.user_head_url + userLoginBean.getImage_url());
                session.setAttribute("id", userLoginBean.getDevId());
                session.setAttribute("user", userLoginBean);
                // 记住密码功能实现
                if (rememberMe != null && rememberMe == 1) {
                    String key = IJedisService.putUserToRedis(userLoginBean.getDevId() + "", info, flag);
                    map.put("key", key);
                }
                String token = MD5.encode(new Date().getTime() + "" + userLoginBean.getDevId());
                int i = IJedisService.setUserByToken(userLoginBean.getDevId(), token);
                if (i > 0) {
                    session.setAttribute("token", token);
                    map.put("token", token);
                    System.out.println(token);
                    map.put("message", "1");
                    logger.info("用户" + username + " 登录成功");
                } else {
                    map.put("message", "0");
                    logger.warn("用户" + username + " 登录失败（redis令牌设置异常）");
                }
            } else {
                map.put("message", "-1");
                logger.info("用户" + username + " 账号或密码错误，登录失败");
            }
        } catch (Exception e) {
            map.put("message", "0");
            logger.error("用户登录异常", e);
        }
        return map;
    }


    /**
     * 发送邮箱验证码
     *
     * @param email   用户邮箱
     * @param session
     * @return
     */
    @RequestMapping(value = "/ajaxGetCodeToEmail")
    @ResponseBody
    public String ajaxGetCodeToEmail(String email, HttpSession session) {
        Integer id = userLoginService.hasEmail(email);
        if (id != null) {
            UserInfoDto user = userLoginService.getUser(id);
            ValidateCodeUtil.writeCodeToEmail(email, user.getName(), session);
            session.setAttribute("sid", id);
            logger.info("用户" + id + " 邮箱" + email + " 获取验证码");
            return "1";
        }
        return "-1";
    }

    /**
     * 发送手机验证码
     *
     * @param mobile  用户手机
     * @param session
     * @return 用户id
     */
    @RequestMapping(value = "/ajaxGetCodeToMobile")
    @ResponseBody
    public String ajaxGetCodeToMobile(String mobile, HttpSession session) {
        Integer id = userLoginService.hasPhone(mobile);
        if (id != null) {
            ValidateCodeUtil.writeCodeToMobile(mobile, session);
            session.setAttribute("sid", id);
            logger.info("用户" + id + " 手机号码" + mobile + " 获取验证码");
            return "1";
        }
        return "-1";
    }

    /**
     * 邮箱方式重置密码验证码校验
     *
     * @param code    用户
     * @param session
     * @return
     */
    @RequestMapping(value = "/ajaxValidateCodeOfEmail")
    @ResponseBody
    public String ajaxValidateCodeOfEmail(String code, HttpSession session) {
        Integer id = (Integer) session.getAttribute("sid");
        if (id != null) {
            UserInfoDto user = userLoginService.getUser(id);
            if (user != null) {
                String code1 = (String) session.getAttribute(user.getEmail());
                if (FormValidateUtil.isCode(code1, code, true)) {
                    return "1";
                }
            }
        }
        return "-1";
    }

    /**
     * 手机方式重置密码验证码校验
     *
     * @param code    用户输入验证码
     * @param session
     * @return
     */
    @RequestMapping(value = "/ajaxValidateCodeOfMobile")
    @ResponseBody
    public String ajaxValidateCodeOfMobile(String code, HttpSession session) {
        Integer id = (Integer) session.getAttribute("sid");
        if (id != null) {
            UserInfoDto info = userLoginService.getUser(id);
            if (info != null) {
                String code1 = (String) session.getAttribute(info.getMobile());
                if (FormValidateUtil.isCode(code1, code, true)) {
                    return "1";
                }
            }
        }
        return "-1";
    }

    /**
     * 修改用户密码
     *
     * @param password 用户输入的新密码
     * @return
     */
    @RequestMapping(value = "/ajaxResetPassword")
    @ResponseBody
    public String ajaxResetPassword(String password, HttpSession session) {
        Integer id = (Integer) session.getAttribute("sid");
        if (id != null && FormValidateUtil.isPassword(password)) {
            userLoginService.resetPassword(password, id);
            logger.info("用户" + id + "修改密码 成功");
            return "1";
        }
        return "-1";
    }

    /**
     * 获取重置密码用户信息
     *
     * @return
     */
    @RequestMapping("/ajaxGetUserForResetPwd")
    @ResponseBody
    public UserInfoDto ajaxGetUserForResetPwd(HttpSession session) {
        Integer id = (Integer) session.getAttribute("sid");
        UserInfoDto user = userLoginService.getUser(id);
        return user;
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @RequestMapping("/ajaxGetUser")
    @ResponseBody
    public UserInfoDto ajaxGetUser(HttpSession session) {
        String token = (String) session.getAttribute("token");
        if (token != null) {
            UserInfoDto user = IJedisService.getUserByToken(token);
            //用户为空说明令牌失效,清除session数据
            if (user == null) {
                session.invalidate();
            } else {
                session.setMaxInactiveInterval(30 * 60);
            }
            return user;
        }
        return null;
    }

    /**
     * 用户退出
     */
    @ResponseBody
    @RequestMapping("/ajaxLogout")
    public String ajaxLogout(HttpSession session) throws Exception {
        Long i = 0L;
        String token = (String) session.getAttribute("token");
        if (FormValidateUtil.isNotEmpty(token)) {
            i = IJedisService.clearUserByToken(token);
        }
        Object id = session.getAttribute("id");
        session.invalidate();
        logger.info("用户" + id + "退出 成功");
        return String.valueOf(i);
    }

    /**
     * 远程获取登录用户信息
     *
     * @param token    用户登录令牌
     * @param callback jsonp回调函数
     * @return
     */
    @RequestMapping(value = "/ajaxGetUserByJsonp", method = {RequestMethod.GET, RequestMethod.POST}, produces = {"text/html;charset=UTF-8;"})
    @ResponseBody
    public String ajaxGetUserByJsonp(String token, String callback) throws UnsupportedEncodingException {
        if (FormValidateUtil.isNotEmpty(token) && FormValidateUtil.isNotEmpty(callback)) {
            UserInfoDto userInfo = IJedisService.getUserByToken(token);
            if (userInfo != null) {
                String user = JsonUtil.toJSon(userInfo);
                String encode = URLEncoder.encode(user, "utf-8");
                String s = callback + "('" + encode + "')";
                return s;
            }
        }
        return null;
    }

    /**
     * 远程用户退出
     *
     * @param token    令牌
     * @param callback jsonp回调函数
     * @return
     */
    @RequestMapping("/ajaxLogoutByJsonp")
    @ResponseBody
    public String ajaxLogoutByJsonp(String token, String callback) {
        Long i = 0L;
        if (FormValidateUtil.isNotEmpty(token)) {
            i = IJedisService.clearUserByToken(token);
        }
        return callback + "(" + i + ")";
    }

    /**
     * 获取系统运行信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSystemInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getSystemInfo(HttpServletRequest request, String callback) {
        SystemInfo systemInfo = null;
        Map<String, Object> info = new HashMap<>();
        try {
            systemInfo = SystemInfo.getInstance(request);
            info.put("message", "1");
            info.put("data", systemInfo);
        } catch (Exception e) {
            info.put("message", "-1");
            info.put("error", e);
            e.printStackTrace();
        }
        String s = JsonUtil.toJSon(info);
        return callback + "(" + s + ")";
    }
}
